#include "propdelegate.h"
#include <QtGui>

PropDelegate::PropDelegate(QObject *parent)
    : QItemDelegate(parent)
{
	
}

QWidget *PropDelegate::createEditor(QWidget *parent,
    const QStyleOptionViewItem &/* option */,
    const QModelIndex & index ) const
{
	QWidget *editor=NULL;
	int role = index.model()->data(index,Qt::UserRole).toInt();
	switch(role){
		case PROP_TEXT:
			editor = new QLineEdit(parent);		
			break;
		case PROP_NUM:
			editor = new QSpinBox(parent);
			((QSpinBox*)editor)->setMaximum(2048);
			break;
		case PROP_COMBO:
			editor = new QComboBox(parent);	
			((QComboBox*)editor)->insertItems(0,index.model()->data(index,Qt::UserRole+1).toStringList()); // заполнение координатами
			break;
	}

	if(editor)
		editor->installEventFilter(const_cast<PropDelegate*>(this));		
    return editor;
}

void PropDelegate::setEditorData(QWidget *editor,
                                    const QModelIndex &index) const
{
    QString value = index.model()->data(index, Qt::DisplayRole).toString();
	int role = index.model()->data(index,Qt::UserRole).toInt();
	
	QLineEdit *edt1;
	QSpinBox  *edt2;
	QComboBox *edt3;
	//QCheckBox *edt4;

	switch(role){
	    case PROP_TEXT:
		    edt1 = static_cast<QLineEdit*>(editor);
		    edt1->setText(value);		
		    break;		
		case PROP_NUM:
	    	edt2 = static_cast<QSpinBox*>(editor);
	    	edt2->setValue(value.toInt());		 
	    	break;  
	    case PROP_COMBO:
		    edt3 = static_cast<QComboBox*>(editor);
		    edt3->setCurrentIndex(edt3->findText(value));
		    edt3->insertItem(0,"");		
		    break;		
	}
}

void PropDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                   const QModelIndex &index) const
{
	QString value;
	QLineEdit *edt1;
	QSpinBox  *edt2;
	QComboBox *edt3;
	//QCheckBox *edt4;

	int role = index.model()->data(index,Qt::UserRole).toInt();
	switch(role){
	    case PROP_TEXT:
		    edt1  = static_cast<QLineEdit*>(editor);
			value = edt1->text();		
		    break;
		case PROP_NUM:
		    edt2 = static_cast<QSpinBox*>(editor);
		    edt2->interpretText();
		    value = QString("%1").arg(edt2->value());		    		
		    break;
	    case PROP_COMBO:
		    edt3  = static_cast<QComboBox*>(editor);
		    value = edt3->currentText();
		    break;		
	}


    model->setData(index, value);
}

void PropDelegate::updateEditorGeometry(QWidget *editor,
    const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
    editor->setGeometry(option.rect);
}
